<?php
// 应用公共文件

// layui表格数据结构
function table($data=[],$count=0,$msg='success',$code=0){
    $result['code']  = $code;
    $result['msg']   = $msg;
    $result['count'] = $count;
    $result['data']  = $data;
    return json($result);
}

function ping_time($ip) {
    $ping_cmd = "ping -c 3 -w 5 " . $ip;
    $info = [];
    exec($ping_cmd, $info);
    $ping_time_line = end($info);

    $ping_time = explode("=", $ping_time_line)[1];
    $ping_time_min = explode("/", $ping_time)[0] / 1000.0;
    $ping_time_avg = explode("/", $ping_time)[1] / 1000.0;
    $ping_time_max = explode("/", $ping_time)[2] / 1000.0;

    $result = array();
    $result['ping_min'] = $ping_time_min;
    $result['ping_avg'] = $ping_time_avg;
    $result['ping_max'] = $ping_time_max;

    print_r($result);
}

/**
 * 数组层级缩进转换
 * @param array $array 源数组
 * @param int   $pid
 * @param int   $level
 * @return array
 */
function array2level($array, $pid = 0, $level = 1)
{
    static $list = [];
    foreach ($array as $v) {
        if ($v['pid'] == $pid) {
            $v['level'] = $level;
            $list[]     = $v;
            array2level($array, $v['id'], $level + 1);
        }
    }
    return $list;
}

#无限极处理
 function getTree($data,$pid=0)
{
    $tree = [];
    foreach ( $data as $key => $row) {
        if($row['pid'] == $pid){
            $children = getTree($data,$row['id']);
            if(!empty($children)){
                $row['children'] = $children;
            }
            $tree[] = $row;
        }
    }
    return $tree;
}
// 返回成功
function suc($msg='成功',$code=1){
    return json(['code'=>$code,'msg'=>$msg,'icon'=>6]);
}
// 返回失败
function err($msg='失败',$code=0){
    return json(['code'=>$code,'msg'=>$msg,'icon'=>5]);
}

# 域名获取
function getDomain(){

    return request()->domain();
}

/**
 * 转化数据库保存图片的文件路径，为可以访问的url
 * @param string $file  文件路径，数据存储的文件相对路径
 * @return string 图片链接
 */
function get_image_url($file)
{
    if (empty($file)) {
        return '';
    }
    return getDomain() . $file;
}

